//
//  shopApp.swift
//  shop
//
//  Created by chen on 2025/5/12.
//

import SwiftUI
import ATAuthSDK

@main
struct ShopApp: App {
    
    @StateObject private var router = Router.shared
    @StateObject private var authManager = AuthManager.shared
    
    init() {
        initAuthKey()
    }
    
    var body: some Scene {
        WindowGroup {
            NavigationStack(path: $router.path){
                ContentView()
                    .preferredColorScheme(.light) // 强制使用浅色模式
                    .navigationDestination(for: AppRoute.self) { route in
                        switch route {
                        case .contentView(let selectTab):
                            ContentView(selectTab: selectTab)
                        case .detailView(let id):
                            DetailView(id: id)
                        case .hotView:
                            HotView()
                        case .searchView:
                            SearchView()
                        case .searchResult(let keyWord):
                            SearchResult(keyWord: keyWord)
                        case .loginView:
                            LoginView()
                        case .registerView:
                            RegisterView()
                        }
                    }
            }
            .environmentObject(router)
            .environmentObject(authManager)
        }
    }
    
    private func initAuthKey() {
        Task{
            let instance = ATAuthSDK.TXCommonHandler.sharedInstance()
            await NetManager.server.httpGet(.authKey) { (info: String) in
                instance.setAuthSDKInfo(info) { (data: [AnyHashable : Any]) in
                    Logger.shared.info("setAuthSDKInfo:\(data)")
                    if data["resultCode"] as! String == "600000" {
                        self.checkEnv()
                    }
                }
            }
        }
    }
    
    private func checkEnv() {
        let instance = ATAuthSDK.TXCommonHandler.sharedInstance()
        instance.checkEnvAvailable(with: PNSAuthType.loginToken) { (data: [AnyHashable : Any]?) in
            if let data = data, data["resultCode"] as! String == "600000"  {
                instance.accelerateLoginPage(withTimeout: TimeInterval(3)) { (checkData: [AnyHashable : Any]) in
                    if checkData["resultCode"] as! String == "600000" {
                        AuthManager.shared.oneKeyLoginSupport = true
                        return
                    }
                }
            }
        }
    }
}
